package com.sneakxy.actions;

import java.sql.SQLException;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Options;
import org.apache.commons.lang3.StringUtils;

import com.sneakxy.config.Config;
import com.sneakxy.jdbc.JdbcHelper;

public class ActionDelete implements Action {

	private JdbcHelper helper;
	
	private Config config;
	
	@Override
	public void execute(CommandLine command, Options options) throws Exception {
		this.config = createConfig(command, options);
		this.helper = this.config.getJdbc().createJdbcHelper();
		try {
			helper.openConnection();
			int size = config.getTable().getSize();
			String tableOldName = config.getTable().getName();
			String dropSql = null;
			String tableName = null;
			dropSql = createDropSql(tableOldName);
			dropTable(helper, tableOldName, dropSql);
			for(int i=0; i<size; i++) {
				tableName = StringUtils.join(tableOldName, "_", i);
				dropSql = createDropSql(tableName);
				dropTable(helper, tableName, dropSql);
			}
		} catch (ClassNotFoundException e) {
			System.out.println("驱动加载失败.");
		} catch (SQLException e) {
			System.out.println("数据库操作失败.");
			e.printStackTrace();
		} finally {
			if(helper != null) {
				helper.close();
			}
		}
	}
	
	protected String createDropSql(String table) {
		return StringUtils.join("DROP TABLE IF EXISTS ", table);
	}
	
	protected void dropTable(JdbcHelper helper, String table, String dropSql) {
		try {
			helper.update(dropSql);
			System.out.println(String.format("删除%s成功.", table));
		} catch(Exception ex) {
			System.out.println(String.format("删除%s失败.", table));
		}
	}

}
